package com.ncloud.crm.dubboservice.impl;

import java.util.Date;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.ncloud.common.enmus.ResultEnum;
import com.ncloud.common.exception.UserException;
import com.ncloud.crm.business.OrderInfoBusi;
import com.ncloud.crm.common.Constant;
import com.ncloud.crm.dubboservice.WorkDubboService;
import com.ncloud.crm.entity.order.Order;
import com.ncloud.crm.entity.order.OrderCustomer;
import com.ncloud.crm.entity.order.Work;
import com.ncloud.crm.entity.order.WorkAttr;
import com.ncloud.crm.entity.order.WorkNode;
import com.ncloud.crm.entity.order.WorkNodeAttr;
import com.ncloud.crm.entity.order.WorkNodeEqpt;
import com.ncloud.crm.entity.order.WorkNodeNetAccess;
import com.ncloud.crm.service.BsNodeService;
import com.ncloud.crm.service.OrderCustomerService;
import com.ncloud.crm.service.OrderService;
import com.ncloud.crm.service.WorkAttrService;
import com.ncloud.crm.service.WorkNodeAttrService;
import com.ncloud.crm.service.WorkNodeEqptService;
import com.ncloud.crm.service.WorkNodeNetAccessService;
import com.ncloud.crm.service.WorkNodeService;
import com.ncloud.crm.service.WorkService;
import com.ncloud.crm.utils.OrderNodeDefineUtils;

@Service
public class WorkDubboServiceImpl implements WorkDubboService {
	@Autowired
	private WorkService workService;
	@Autowired
	private WorkNodeService workNodeService;
	@Autowired
	private BsNodeService bsNodeService;
	@Autowired
	private WorkNodeAttrService nodeAttrService;
	@Autowired
	private WorkNodeEqptService eqptService;
	@Autowired
	private WorkNodeNetAccessService accessService;
	@Autowired
	private WorkAttrService workAttrService;
	@Autowired
	private OrderInfoBusi busiService;
	@Autowired
	private OrderCustomerService orderCustomerService;
	@Autowired
	private OrderService orderService;
	
	@Override
	public JSONArray getWorkList(JSONObject json) {
		if(!json.containsKey("orderId")){
			throw new UserException(ResultEnum.PARAM_ERROR);
		}
		String orderState = null;
		if(json.containsKey("orderState")){
			orderState = json.getString("orderState");
		}
		Long orderId = json.getLong("orderId");
		List<Map<String,Object>> works = workService.getWorksByOrder(orderId,orderState);
		return JSON.parseArray(JSON.toJSONString(works));
	}

	@Override
	public JSONObject getWorkDetail(JSONObject json) {
		if(!json.containsKey("workId")){
			throw new UserException("2001","传入参数有误");
		}
		Long workId = json.getLong("workId");
		Long orderId = null;
		// 通过workId获取节点信息
		List<WorkNode> workNodes = workNodeService.getNodesByWorkId(workId);
		JSONObject newNode = new JSONObject();
		JSONObject oldNode = new JSONObject();
		for (WorkNode workNode : workNodes) {
			orderId = workNode.getOrderId();
			if(Constant.ADD.equals(workNode.getModifyTag())){
				newNode = workNodeService.getNewNodeInfo(workNode);
//				newNode = getNodeChangeInfo(workNode);
			}else{
				oldNode = workNodeService.getNodeChangeOldInfo(workNode);
//				oldNode = getNodeInstInfo(workNode.getNodeId());
			}
		}
		
		if(orderId != null){
			//获取订单信息
			Order order = orderService.getOrderPk(orderId);
			if(order == null)
				order = orderService.getHisOrderPK(orderId);
			newNode.put("custId", order.getCustId()+"");
			newNode.put("custName", order.getCustName());
			//获取项目联系人信息
//			OrderProject orderProject = orderProjectService.getNewProjectInfo(order);
			OrderCustomer orderCustomer = orderCustomerService.getNewCustomerByOrder(order);
			newNode.put("contactName", orderCustomer.getContactName());
			newNode.put("contactPhone", orderCustomer.getContactPhone());
		}
		//获取工单信息
		Work work = workService.getWorkInfo(workId);
		if(work==null)
			work=workService.getHisWorkInfo(workId);
		newNode.put("workStateName", work.getWorkStateName());
		newNode.put("workState", work.getWorkState());
		JSONObject result = new JSONObject();
		result.put("newNode", newNode);
		result.put("oldNode", oldNode);
		return result;
	}

	@SuppressWarnings("unused")
	private JSONObject getNodeInstInfo(Long nodeId) {
		return bsNodeService.getNodeDetailInfo(nodeId);
	}

	@SuppressWarnings("unused")
	private JSONObject getNodeChangeInfo(WorkNode workNode) {
		Long workId = workNode.getWorkId();
		
		//获取节点属性
		List<WorkNodeAttr> nodeAttrs = nodeAttrService.getNodeAttrsByWorkId(workId);
		nodeAttrs.removeIf(x->!Constant.ADD.equals(x.getModifyTag()));
		
		//获取节点接入信息
		List<WorkNodeNetAccess> nodeNetAccesses = accessService.getNodeIntersByWorkId(workId);
		nodeNetAccesses.removeIf(x->!Constant.ADD.equals(x.getModifyTag()));

		//获取节点设备信息
		List<WorkNodeEqpt> nodeEqpts = eqptService.getNodeEqptsByWorkId(workId);
		nodeEqpts.removeIf(x->!Constant.ADD.equals(x.getModifyTag()));
		
		//获取施工单属性
		List<WorkAttr> workAttrs = workAttrService.getAttrsByWorkId(workId);
		//组织输出参数
		JSONObject nodeJson = new JSONObject();
		if(nodeJson!=null) nodeJson = JSON.parseObject(JSON.toJSONString(workNode,SerializerFeature.WriteMapNullValue));
		JSONArray nodeAttrArray = JSON.parseArray(JSON.toJSONString(nodeAttrs,SerializerFeature.WriteMapNullValue));
		JSONArray workAttrArray = JSON.parseArray(JSON.toJSONString(workAttrs,SerializerFeature.WriteMapNullValue));
		setAttr2Object(nodeAttrArray,nodeJson);
		setAttr2Object(workAttrArray, nodeJson);
		nodeJson.put("nodeNetAccess", JSON.parseArray(JSON.toJSONString(nodeNetAccesses,SerializerFeature.WriteMapNullValue)));
//		nodeJson.put("nodeEqpt", JSON.parseArray(JSON.toJSONString(nodeEqpts)));
		if(nodeEqpts.size()>0)
			nodeJson.put("nodeEqpt",JSON.parseObject(JSON.toJSONString(nodeEqpts.get(0),SerializerFeature.WriteMapNullValue),Feature.IgnoreNotMatch));
		else nodeJson.put("nodeEqpt",new JSONObject());
		return nodeJson;
	}

	private void setAttr2Object(JSONArray nodeAttrArray, JSONObject nodeJson) {
		for(int i=0;i<nodeAttrArray.size();i++){
			JSONObject attr = nodeAttrArray.getJSONObject(i);
			String key = attr.getString("attrCode");
//			if(Constant.DEL.equals(attr.getString("MODIFY_TAG"))){
//				key +="Old";
//			}
			nodeJson.put(key,attr.getString("attrValue"));
		}
	}

	@Override
	public JSONObject completeWork(JSONObject json) {
		if(!json.containsKey("workId"))
			throw new UserException("2001","传入参数有误");
		JSONObject jsonObject = busiService.completeWork(json);
		return jsonObject;
	}

	@Override
	public JSONObject callBackWorkAttr(JSONObject jsonObject) {
		JSONObject json = new JSONObject();
		if(jsonObject.containsKey("workId") && jsonObject.containsKey("nodeId")){
			if(!jsonObject.containsKey(OrderNodeDefineUtils.WORK_ITEM)){
				throw new UserException("工单属性信息不存在！");
			}
			json = busiService.callBackWorkAttr(jsonObject);
		}else{
			throw new UserException(ResultEnum.ORDER_INFO_ERROR);
		}
		return json;
	}

	@Override
	public JSONObject changeWorkDoing(JSONObject json) {
		// 判断传入参数是否正确
		if(!json.containsKey("workId")){
			throw new UserException("2001","传入参数有误");
		}
		Long workId = json.getLong("workId");
		Long userId = json.getLong("userID");
		Work work = new Work();
		work.setWorkId(workId);
		work.setConstructUser(userId);
		work.setWorkState(Constant.WORK_STATE_DOING);
		work.setConstructTime(json.containsKey("constructTime")?json.getDate("constructTime"):new Date());
		workService.updateWorkState(work);
		return new JSONObject();
	}

	@Override
	public JSONObject nodeLogisticsInfo(JSONObject jsonObject) {
		// 判断传入参数是否正确
		if(!jsonObject.containsKey("workId")){
			throw new UserException("2001","传入参数有误,workId不存在！");
		}
		//company
		if(!jsonObject.containsKey("companyId")){
			throw new UserException("2001","传入参数有误,companyId不存在！");
		}
		if(!jsonObject.containsKey("company")){
			throw new UserException("2001","传入参数有误,company不存在！");
		}
		//out_logistics_id
		if(!jsonObject.containsKey("outLogisticsId")){
			throw new UserException("2001","传入参数有误,outLogisticsId不存在！");
		}
		busiService.completeNodeLogistics(jsonObject);
		return new JSONObject();
	}
}
